package logic

import (
	"context"
	"fmt"
	"person/mobels/cache"
	"person/mobels/mysql"
	"person/pkg"

	"person/personrpc/internal/svc"
	"person/personrpc/personrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *personrpc.UserRegisterRequest) (*personrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendSms"+"register"+in.Mobile)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("验证码错误，请重新输入")
	}

	var find mysql.User
	mysql.DB.Where("mobile = ?", in.Mobile).Find(&find)
	if find.ID != 0 {
		return nil, fmt.Errorf("手机号已被注册，请换号重试")
	}

	var findAccount mysql.User
	mysql.DB.Where("account = ?", in.Account).Find(&findAccount)
	if findAccount.ID != 0 {
		return nil, fmt.Errorf("账号已存在，禁止账号重复注册")
	}

	var user mysql.User
	user = mysql.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
		Mobile:   in.Mobile,
	}

	err := mysql.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	cache.Rdb.Del(l.ctx, "sendSms"+"register"+in.Mobile)
	return &personrpc.UserRegisterResponse{Id: int64(user.ID)}, nil
}
